package com.chen.project.white_jotter.service;

import com.chen.project.white_jotter.mapper.BookMapper;
import com.chen.project.white_jotter.pojo.Book;
import com.chen.project.white_jotter.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class LibraryService {

    @Resource
    private BookMapper bookMapper;
    @Resource
    CategoryService categoryService;
    @Resource
    private RedisUtil redisUtil;


    // 获取所有图书
    public List<Book> getAllBooks() {

        List<Book> bookList = null;

        if(redisUtil.get("book_list") != null){
           bookList = (List<Book>) redisUtil.get("book_list");
        }
        else{
            bookList = bookMapper.selectList(null);
            redisUtil.set("book_list", bookList);
            redisUtil.expire("book_list", 20L, TimeUnit.MINUTES);
        }
        return bookList;
    }

    // 获取一个分类的图书
    public List<Book> getBooksByCategoryId(int cid) {

        List<Book> bookList = null;

        if(redisUtil.get("book_list_"+cid) != null){
            bookList = (List<Book>) redisUtil.get("book_list_"+cid);
        }
        else{
            System.out.println("从数据库获取["+cid+"]图书");
            bookList = bookMapper.selectAllByCategory(cid);
            redisUtil.set("book_list_"+cid, bookList);
            redisUtil.expire("book_list_"+cid, 20L, TimeUnit.MINUTES);
        }

        return bookList;
    }

    // mysql搜索
    public List<Book> searchBooks(String keyword) {
        return bookMapper.selectAllByTitleLikeOrAuthorLike(keyword, keyword);
    }

}
